package com.itlxd.filter;

import com.alibaba.fastjson.JSON;
import com.itlxd.common.ThreadLocalUtils;
import com.itlxd.entity.Employee;
import com.itlxd.entity.User;
import com.itlxd.global.SysConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: lixiaodong
 **/
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/backend/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();

        boolean match = checkUriIsPass(uri);
        //判断是否是不需要拦截的路径
        if (match) {
            filterChain.doFilter(request, response);
            return;
        }

        //用户已登陆 放行
        Object loginEmployee = request.getSession().getAttribute(SysConstants.LOGIN_EMPLOYEE);
        if (null != loginEmployee) {
            ThreadLocalUtils.setCurrentId(((Employee) loginEmployee).getId());
            filterChain.doFilter(request, response);
            return;
        }

        //用户未登录
        log.info("用户未登录");
        log.info("拦截的路径：" + uri);
        //5、如果未登录则返回登陆页面
        response.setContentType("text/html;charset=utf-8");
        //response.getWriter().write(JSON.toJSONString(ResultVO.error(SysConstants.NO_LOGIN, SysMessages.NO_LOGIN)));
        response.sendRedirect(SysConstants.LOGIN_HTML);
    }

    /**
     * 检查拦截的uri是否要放行
     */
    private static boolean checkUriIsPass(String uri) {
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/api/**",
                "/backend/images/**",
                "/backend/js/**",
                "/backend/plugins/**",
                "/backend/styles/**",
                "/**/login.html",
                "/front/**",
                "/common/*",
                "/user/login",
                "/user/sendMsg"
        };

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
